/**
 * Created by Administrator on 2017/6/6.
 */
var fs = require('fs');
var MJPlayer = require('../MJ/player').MJPlayer;
var MJ = require('../MJ/MJ');
var Const = require('./const');
var SubCode = require('../subCode');
var huLogic = require('./huLogic');
var mapObj = JSON.parse(fs.readFileSync('./app/logic/sub/YZMJ/map1.json'));
exports.YZMJPlayer = MJPlayer.extend({
    init: function (uid, msg) {
        this._super(uid, msg);

        this._stat.zmCount = 0;             // 自摸次数
        this._stat.dpCount = 0;             // 点炮次数
        this._stat.dhCount = 0;             // 点胡次数
        this._stat.anGangCount = 0;        // 暗杠次数
        this._stat.mingGangCount = 0;      // 明杠次数
        this._stat.roundanGang = 0;        // 本轮暗杠次数
        this._stat.roundmingGang = 0;      // 本轮明杠次数
        this._stat.roundbaGang = 0;         //补杠次数

        this._stat.lzCount = 0;             // 庄家次数
        this._stat.roundRules = {};         //规则
        this._hundiao = false;              //是否是会儿吊
        //this.scoreStatus = null;            //本轮结算分状态
        this._stat.ffCounts = 0;            //放风次数
        this._stat.fjCounts = 0;            //放箭次数
        this.gangScore = 0;                 //杠的分数
        this.dianGangScore = 0
        this.ffScore = 0;
        this.fjScore = 0;
        this.mengScore = 0;
        this.baseScore = 0;
        this.genZScore = 0;
        this.dianGangStatus = 0;
        this.isFF = false;
        this.isFJ = false;

        this.played3XCount = 0;             // 吃碰杠放风放箭次数
    },
    reset: function () {
        this._stat.roundanGang = 0;        // 本轮暗杠次数
        this._stat.roundmingGang = 0;      // 本轮明杠次数
        this._stat.roundbaGang = 0;         //补杠次数
        this._hundiao = false;              //是否是会儿吊
        //this.scoreStatus = null;            //本轮结算分状态
        this._stat.ffCounts = 0;            //放风次数
        this._stat.fjCounts = 0;            //放箭次数
        this.gangScore = 0;                 //杠的分数
        this.dianGangScore = 0
        this.ffScore = 0;
        this.fjScore = 0;
        this.mengScore = 0;
        this.baseScore = 0;
        this.genZScore = 0;
        this.dianGangStatus = 0;
        this.isFF = false;
        this.isFJ = false;

        this.lastFJorHRG = false;

        this.played3XCount = 0;             // 吃碰杠放风放箭次数
    },
    // setStatusScore: function (score) {
    //     if (score) {
    //         this.scoreStatus = score;
    //     } else {
    //         this.scoreStatus = {
    //             'baseScore': 0,
    //             'gangScore': 0,
    //             'ffScore': 0,
    //             'fjScore': 0,
    //             'mengScore': 0
    //         }
    //     }
    // },
    getgenZScore: function () {
        return this.genZScore;
    },
    getSumScore: function () {
        return this.getBaseScore() + this.getGangScore() + this.getMengScore() + this.getDianGangScore() + this.getgenZScore();
    },
    getBaseScore: function () {
        return this.baseScore;
    },
    getGangScore: function () {
        return this.gangScore + this.getffScore() + this.getfjScore();
    },
    getMengScore: function () {
        return this.mengScore;
    },
    getffScore: function (score) {
        return this.ffScore;
    },
    getfjScore: function (score) {
        return this.fjScore;
    },
    getDianGangScore: function () {
        return this.dianGangScore;
    },
    addgenZScore: function (score) {
        this.genZScore += score;
    },
    addMengScore: function (score) {
        this.mengScore += score;
    },
    addBaseScore: function (score) {
        this.baseScore += score;
    },
    addDianGangScore: function (score, where) {
        this.dianGangScore += score
    },
    addGangScore: function (score) {
        this.gangScore += score;
    },
    addffScore: function (score) {
        this.ffScore += score
    },
    addfjScore: function (score) {
        this.fjScore += score;
    },
    //不能吃
    checkChiCondition: function (card) {
        return false;
    },
    //处理吃任务
    chiCard: function (chiTask) {
        return false;
    },
    checkFF: function () {
        var dfNum = this._handCards.getCardNum(MJ.ZI.DF);
        var nfNum = this._handCards.getCardNum(MJ.ZI.NF);
        var xfNum = this._handCards.getCardNum(MJ.ZI.XF);
        var bfNum = this._handCards.getCardNum(MJ.ZI.BF);

        var ffNum = Math.min(dfNum, nfNum, xfNum, bfNum);
        var ffAarray = [];
        for (var i = 0; i < ffNum; ++i) {
            ffAarray.push({ type: Const.Type.FF });
        }
        return ffAarray;
    },
    FFCard: function (task) {
        this._handCards.delCard(MJ.ZI.DF);
        this._handCards.delCard(MJ.ZI.NF);
        this._handCards.delCard(MJ.ZI.BF);
        this._handCards.delCard(MJ.ZI.XF);
        return { type: Const.Type.FF };
    },

    checkFJ: function () {
        var hzNum = this._handCards.getCardNum(MJ.ZI.HZ);
        var bbNum = this._handCards.getCardNum(MJ.ZI.BB);
        var fcNum = this._handCards.getCardNum(MJ.ZI.FC);

        var fjNum = Math.min(fcNum, bbNum, hzNum);
        var fjAarray = [];
        for (var i = 0; i < fjNum; ++i) {
            fjAarray.push({ type: Const.Type.FJ });
        }
        return fjAarray;
    },
    FJCard: function (task) {
        this._handCards.delCard(MJ.ZI.HZ);
        this._handCards.delCard(MJ.ZI.FC);
        this._handCards.delCard(MJ.ZI.BB);
        return { type: Const.Type.FJ };
    },

    checkHPG: function (card) {

    },
    //增加会儿皮明暗杠
    checkGang: function () {
        var room = this.getRoom();
        var gangArray = [];
        var huip = room.getHuiP();
        var lastCard = this._handCards.getLastNewCard();
        if (this.getIndex() != room.getCurPlay() || room.getCurTask()) {
            lastCard = 0;
        }

        if (lastCard) { //优先杠刚摸上的牌
            if (lastCard == huip) {
                if (this._handCards.getCardNum(lastCard) == 3) {
                    gangArray.push({ card: lastCard, gang: Const.Gang.HAN });
                }
            } else {
                if (this._handCards.getCardNum(lastCard) == 4) {
                    gangArray.push({ card: lastCard, gang: Const.Gang.AN });
                }

                if (this._pengCards.indexOf(lastCard) != -1) {
                    gangArray.push({ card: lastCard, gang: Const.Gang.BA });
                }
            }
        }

        var anGangCards = this._handCards.getAnGangCards();
        var huiGangCard = this._gethuiGangCards(); //获取手牌中可以会儿皮杠的牌

        if (huiGangCard && huiGangCard != lastCard) {
            gangArray.push({
                card: huip,
                gang: Const.Gang.HANS
            });
        }
        //去除会儿皮
        anGangCards = anGangCards.filter(function (v) {
            return v != huip;
        });
        for (var i = 0; i < anGangCards.length; ++i) {
            if (anGangCards[i] != lastCard) {
                var gangInfo = { card: anGangCards[i], gang: Const.Gang.ANS };
                if (this.getRoom().getHideOption("anGangOverdue")) {
                    if (this.getPlayHand() != this.getRoom().getCurGang()) {
                        gangInfo.overdue = true;
                    }
                }
                gangArray.push(gangInfo);
            }
        }

        this._pengCards.forEach(function (card) {
            if (this._handCards.getCardNum(card) > 0) {
                if (card != lastCard) {
                    gangArray.push({ card: card, gang: Const.Gang.BA, overdue: true });
                }
            }
        }.bind(this));

        var from = this.getIndex();
        gangArray.forEach(function (gangInfo) {
            gangInfo.from = from;
        });
        console.log("gangarray")
        console.log(gangArray);
        return gangArray;
    },
    //检查手牌中有无会儿皮暗杠
    _gethuiGangCards: function () {
        var room = this.getRoom();
        if (this._handCards.getCardNum(room.getHuiP()) == 3) {
            return room.getHuiP();
        }
        return false;
    },
    checkGangWithCard: function (card) {
        var room = this.getRoom();
        // if (card == room.getBaoCard()) {
        //     return false;
        // }
        var huip = this.getRoom().getHuiP();
        if (huip == card) {
            return (this._handCards.getCardNum(card) == 2);
        }
        return (this._handCards.getCardNum(card) == 3);
    },
    //处理杠牌信息
    gangCard: function (gangTask) {
        var selectGang = gangTask.selectGang || 0;
        if (selectGang > gangTask.gangArray.length) {
            selectGang = 0;
        }

        var selectGangTask = gangTask.gangArray[selectGang];

        var from = selectGangTask.from;
        var card = selectGangTask.card;
        var gang = selectGangTask.gang;
        var room = this.getRoom();
        var huip = room.getHuiP();
        var playerIndex = this.getIndex();
        var targets = [];
        var type = false;
        switch (gang) {
            case Const.Gang.BA:
                var indexOfPeng = this._pengCards.indexOf(card);
                if (indexOfPeng != -1) {
                    this._handCards.delCard(card);
                    this._pengCards.splice(indexOfPeng, 1);
                }
                break;
            case Const.Gang.HDIAN:
                this._HdianGang(huip);
                var fromPlayer = this.getRoom().getPlayerByIndex(from);
                if (fromPlayer) {
                    fromPlayer.setLastPlayCardTask(MJ.Task.GANG);
                }
                break;
            case Const.Gang.DIAN:
                this._handCards.dianGang(card);

                var fromPlayer = this.getRoom().getPlayerByIndex(from);
                if (fromPlayer) {
                    fromPlayer.setLastPlayCardTask(MJ.Task.GANG);
                }
                break;
            case Const.Gang.AN:
            case Const.Gang.ANS:
                this._handCards.anGang(card);
                break;
            case Const.Gang.HAN:
            case Const.Gang.HANS:
                this._HanGang(huip);
                break;
            default:
                break;
        }

        if (gang == MJ.Gang.DIAN || gang == Const.Gang.HDIAN) {
            targets.push(from);
        } else {
            this.getRoom().enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    targets.push(eIndex);
                }
            });
        }

        var gangInfo = clone(selectGangTask);
        //会儿杠不补牌
        if (gang == Const.Gang.HDIAN || gang == Const.Gang.HAN ||
            gang == Const.Gang.HANS) {
            gangInfo.type = true;
        }
        delete gangInfo.playerIndex;
        gangInfo.targets = targets;
        this._gangCards.push(gangInfo);

        logger.debug("room=%d index=%d gangCard card=%d cards=%j", this.getRoom().rid(), this.getIndex(), card, this._handCards.getCards());
        console.log(gangInfo);
        return gangInfo;


    },
    _HdianGang: function (huip) {
        var num = this._handCards.getCardNum(huip)
        if (num != 2) {
            return false;
        }
        this._handCards.delCard(huip);
        this._handCards.delCard(huip);
        return true;
    },
    _HanGang: function (huip) {
        var num = this._handCards.getCardNum(huip)
        if (num != 3) {
            return false;
        }
        this._handCards.delCard(huip);
        this._handCards.delCard(huip);
        this._handCards.delCard(huip);
        return true;
    },

    // settlementGangScore: function () {
    //     var player = this;
    //     var room = this.getRoom();

    //     /*if (!this.isRoundHu()) {
    //         return;
    //     }*/
    //     for (var i = 0, l = this._gangCards.length; i < l; ++i) {
    //         var gangInfo = this._gangCards[i];
    //         if (gangInfo.type) {
    //             this._stat.roundRules[Const.ScoreRule.JAG] = 1;
    //         } else {
    //             if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
    //                 this._stat.roundanGang++;
    //             } else {
    //                 this._stat.roundmingGang++;
    //             }
    //         }
    //     }
    //     var totalGangScore = (this._stat.roundanGang * 2) + this._stat.roundmingGang;
    //     player.addRoundGangScore(totalGangScore);
    // },

    settlement: function () {
        this.addRoundScore(this.getSumScore());
        if (this.isDealer()) {
            this._stat.lzCount++;
        }

    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/
    //断线重连信息
    getReconnectInfo: function (isSelf) {
        var info = this._super(isSelf);
        info.gangCards = this._gangCards;
        info.pengCards = this._pengCards;
        info.ffCount = this._stat.ffCounts;
        info.fjCount = this._stat.fjCounts;


        return info;
    },

    getSettlementInfo: function () {
        var info = this._super();
        info.gangCards = this._gangCards;

        info.handCards = this._handCards.getCards();

        info.roundanGang = this._stat.roundanGang;
        info.gang = this._gangCards;
        info.BaseScore = this.getBaseScore();
        info.GangScore = this.getGangScore();
        info.DianGang = this.getDianGangScore();
        info.MengScore = this.getMengScore();
        info.genZ = this.getgenZScore();
        return info;
    },
    onStartNewRound: function () {
        this._super();
        this.reset();
    },
    checkHu: function () {
        var cards = this._handCards.getCards();
        return this.checkHuLogic(cards, this.getLastCard());
    },
    checkHunDiao: function () {
        var room = this.getRoom()
        var baoCard = room.getBaoCard();
        var baoCardsNum = room.getBaoCardNum(this);
        var temp1 = this._cardsToCardsArray(this._handCards.getCards())
        if (this.played3XCount == 0) {
            var keys = Object.keys(mapObj);
            var flag1 = true;
            keys.forEach(function (element) {
                if (element != baoCard) {
                    var temp3 = temp1.slice();
                    temp3.push(element);
                    if (huLogic.checkhas4(temp3)) {
                        return;
                    }
                    if (!huLogic.pair7(temp3, baoCardsNum, baoCard)) {
                        flag1 = false;
                    };
                }
            });
            if (flag1 == true) {
                return true;
            }
        }

        var temp = this._cardsToCardsArray(this._handCards.getCards()).filter(function (v) {
            return v != baoCard;
        });


        return huLogic.checkHunDiao(temp, this.played3XCount, room.getBaoCardNum(this), room.getBaoCard());
    },
    /**
     * 检查是否能胡某张牌
     */
    checkHuWithCard: function (card) {
        return MJ.Pattern.NONE
    },
    //检测碰牌
    checkPengWithCard: function (card) {
        var room = this.getRoom();

        if (card == room.huiP) {
            return false;
        }
        return this._handCards.getCardNum(card) >= 2;
    },
    checkHuLogic: function (cards, card) {
        var n = this.played3XCount;
        var room = this.getRoom();
        var arrayCards = this._cardsToCardsArray(cards);
        var baoCard = room.getBaoCard();
        //四会儿胡
        if (room.getBaoCardNum(this) == 4) {
            return Const.Pattern.SHR;
        }
        //判断七对
        if (n == 0) {
            var flag = huLogic.pair7(arrayCards, room.getBaoCardNum(this), baoCard);
            if (flag === 2) {
                return Const.Pattern.HHPAIR7;
            } else if (flag === 1) {
                return Const.Pattern.QPAIR7;
            } else if (flag) {
                return Const.Pattern.PAIR7;
            }
        }
        if (n != 4) {
            var flag = huLogic.checkHuNormal(arrayCards, n);
            if (flag) {
                if (room.getBaoCardNum(this)) {
                    return Const.Pattern.HRGW;
                }
                return Const.Pattern.WHR;
            }
            if (room.getBaoCardNum(this) == 1) {
                var temp = arrayCards.filter(function (v) {
                    return v != baoCard;
                });
                return huLogic.isOneLZ(temp, n) ? Const.Pattern.NORMAL : Const.Pattern.NONE;
            } else if (room.getBaoCardNum(this) == 2) {
                var temp = arrayCards.filter(function (v) {
                    return v != baoCard;
                });
                return huLogic.isTwoLZ(temp, n) ? Const.Pattern.NORMAL : Const.Pattern.NONE;
            } else if (room.getBaoCardNum(this) == 3) {
                var temp = arrayCards.filter(function (v) {
                    return v != baoCard;
                });
                return huLogic.isThreeLZ(temp, n) ? Const.Pattern.NORMAL : Const.Pattern.NONE;
            }
            return Const.Pattern.NONE; //没有赖子且不能胡牌

        } else if (n == 4) {
            var flag = huLogic.checkHu4(arrayCards, room.getBaoCardNum(this))
            
            if (flag) {
                if (!room.getBaoCardNum(this)) {
                    return Const.Pattern.WHR;
                }
                if (flag == 1) {
                    return Const.Pattern.HRGW;
                }
                return Const.Pattern.NORMAL;
            }
            return Const.Pattern.NONE;
        }

    },
    //将牌对象转换为牌数组
    _cardsToCardsArray: function (cards) {
        var keys = Object.keys(cards);
        var temp = [];
        keys.forEach(function (v) {
            var num = cards[v];
            for (var i = 0; i < num; ++i) {
                temp.push(v);
            }
        });
        return temp;
    },
    getInitHandCardPreCards: function () {
        var preCards = [];

        var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
        if (distance == 0) {
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 3));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 9));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 5));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 6));
           // preCards.push(MJ.getValue(MJ.Color.ZI, 7));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 5));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 6));
            // preCards.push(MJ.getValue(MJ.Color.ZI, 7));
            // preCards.push(MJ.getValue(MJ.Color.WAN, 6));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 9));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 9));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 4));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 5));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 5));

            // preCards.push(MJ.getValue(MJ.Color.TONG, 6));
            // preCards.push(MJ.getValue(MJ.Color.TONG, 6));

            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 2));

            // preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
            // preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
        } else if (distance == 1) {
            //preCards.push(MJ.getValue(MJ.Color.WAN, 6));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 1));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 2));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 3));
            //preCards.push(MJ.getValue(MJ.Color.ZI, 4));


        } else if (distance == 2) {
            //preCards.push(MJ.getValue(MJ.Color.WAN, 6));

        } else if (distance == 3) {
            //preCards.push(MJ.getValue(MJ.Color.WAN, 6));

        }


        return preCards;
    },
});